package com.kaka.bus.engine.splash;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.ViewTreeObserver;
import android.widget.ImageView;

import com.kaka.bus.AppCenter;
import com.kaka.bus.R;
import com.kaka.bus.base.BaseActivity;
import com.kaka.bus.bean.HttpWrapper;
import com.kaka.bus.bean.Version;
import com.kaka.bus.constant.Constant;
import com.kaka.bus.down.service.DownloadService;
import com.kaka.bus.engine.Guide.GuideActivity;
import com.kaka.bus.engine.HomeActivity;
import com.kaka.bus.util.StatusBarUtil;
import com.kaka.bus.util.logger.Logger;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.lang.ref.WeakReference;

import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by zhangqi on 2016/10/8.
 * e-mail : ${email}
 * desc :
 */

public class SplashActivity extends BaseActivity<SplashPresenter> implements SplashContract.View {

    public static final int OTHER_ANIM = 0;
    public static final int CHECK_UPDATE = 10;

    public static final int CIRCLE_ANIM = 1;

    public static final int LOGO_ANIM = 2;
    public static final int LOGO_TEXT_ANIM = 3;
    public static final int BOTTOM_TEXT_ANIM = 4;
    public static final int LOGO_LIGHT_BG = 5;
    public static final int LOGO_LIGHT = 6;

    //    @BindView(R.id.tv)
//    TextView mTv;
//    @BindView(R.id.tips)
//    TextView mTips;
    @BindView(R.id.splash_bg)
    ImageView mSplashBg;
    //    @BindView(R.id.splash_logo)
//    ImageView mSplashLogo;
//    @BindView(R.id.splash_bottom)
//    ImageView mSplashBottom;
//    @BindView(R.id.splash_logo_text)
//    ImageView mSplashLogoText;
//    @BindView(R.id.splash_logo_light_bg)
//    ImageView mSplashLogoLightBg;
//    @BindView(R.id.splash_logo_light)
//    ImageView mSplashLogoLight;
    private String mUmeng_channel;
    private long mStartTime;
    private long mDTime;
    private String mDownloadUrl;
    private boolean mIsUpdate;
    private static final int REQUEST_CODE_UPDATE = 20;
    private RxPermissions mRxPermissions;
    private Intent mIntent;

    private HttpWrapper<Version> mData;
    private boolean mCanAnim;
    private SplashHandler mSplashHandler;

    private static class SplashHandler extends Handler {

        private final WeakReference<SplashActivity> mActivty;

        public SplashHandler(SplashActivity activity) {
            mActivty = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            SplashActivity activity = mActivty.get();
            super.handleMessage(msg);
            if (activity != null) {
                switch (msg.what) {
                    case SplashActivity.OTHER_ANIM:
//                        activity.startOtherAnim();
                        break;
                    case SplashActivity.CIRCLE_ANIM:
//                        activity.startCircleAnim();
                        break;
                    case SplashActivity.LOGO_ANIM:
//                        activity.startLogoAnim();
                        break;
                    case SplashActivity.BOTTOM_TEXT_ANIM:
//                        activity.startBottomAnim();
                        break;
                    case SplashActivity.LOGO_TEXT_ANIM:
//                        activity.startLogoTextAnim();
                        break;
                    case SplashActivity.LOGO_LIGHT:
//                        activity.startLoginLightAnim();
                        break;
                    case SplashActivity.LOGO_LIGHT_BG:
//                        activity.startLoginLightBgAnim();
                        break;
                    case SplashActivity.CHECK_UPDATE:
//                        activity.checkUpdate();
                        break;
                }
            }

        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

        /**
         * 用户可以交互了
         */
        if (hasFocus) {
            Log.d(SplashActivity.class.getName(), "动画");

        }
    }

    @Override
    protected void initView() {
        super.initView();
//        EventBus.getDefault().register(this);
        StatusBarUtil.setTranslucentForImageViewInFragment(this, null);

        /**
         * 拿到渠道
         */
        ApplicationInfo appInfo = null;
        try {
            appInfo = this.getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        mUmeng_channel = appInfo.metaData.getString("UMENG_CHANNEL");

        Logger.i("渠道" + mUmeng_channel);

        if (mRxPermissions == null) {
            mRxPermissions = new RxPermissions(this);
        }

        mSplashHandler = new SplashHandler(this);


        mSplashBg.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mSplashBg.getViewTreeObserver().removeOnGlobalLayoutListener(this);

//                checkAnim();
            }
        });
    }

    @Override
    protected void initData() {

        mStartTime = System.currentTimeMillis();
        new Handler().postDelayed(new Runnable() {
            public void run() {
                go();
            }
        }, 2000);
    }

    /**
     * 检查是否能进行动画
     */
//    private void checkAnim() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            mSplashBg.post(() -> {
//                mSplashHandler.sendEmptyMessageDelayed(CIRCLE_ANIM, 800);
//            });
//        } else {
//            mSplashBg.setVisibility(View.VISIBLE);
//            mSplashHandler.sendEmptyMessageDelayed(OTHER_ANIM, 800);
//        }
//    }

    /**
     * 视图扩散动画 支持21以上
     */
//    public void startCircleAnim() {
//        //1.0.2bug  防止动画崩溃
//        int cicular_R = 1920;
//        int width = 1080;
//        int height = 1920;
//        if (mSplashBg != null) {
//            cicular_R = mSplashBg.getHeight();
//            width = mSplashBg.getWidth();
//            height = mSplashBg.getHeight();
//        }
//
//        try {
//            AnimUtil.circularReveal(mSplashBg,
//                    (int) (width * 0.45),
//                    (int) (height * 0.55),
//                    DensityUtil.dp2px(100), cicular_R, new LinearInterpolator(), new AnimatorListener() {
//                        @Override
//                        public void onAnimationStart(Animator animation) {
//                            super.onAnimationStart(animation);
//                            mSplashBg.setVisibility(View.VISIBLE);
//                        }
//
//                        @Override
//                        public void onAnimationEnd(Animator animation) {
//                            super.onAnimationEnd(animation);
//                            mSplashHandler.sendEmptyMessageDelayed(OTHER_ANIM, 0);
//                        }
//                    }).setDuration(500).start();
//        } catch (Exception e) {
//            goHome();
//        } finally {
//
//        }
//    }

//    /**
//     * 其他动画
//     */
//    public void startOtherAnim() {
//        mSplashHandler.sendEmptyMessageDelayed(LOGO_ANIM, 0);
//        mSplashHandler.sendEmptyMessageDelayed(BOTTOM_TEXT_ANIM, 200);
//        mSplashHandler.sendEmptyMessageDelayed(LOGO_TEXT_ANIM, 400);
//        mSplashHandler.sendEmptyMessageDelayed(LOGO_LIGHT, 300);
//        mSplashHandler.sendEmptyMessageDelayed(LOGO_LIGHT_BG, 500);
//    }

    /**
     * logo动画
     */
//    public void startLogoAnim() {
//        Animation scale = AnimUtil.Scale(0f, 1f, 0f, 1f,
//                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f,
//                300, new LinearInterpolator(), new AnimListener() {
//                    @Override
//                    public void onAnimationStart(Animation animation) {
//                        super.onAnimationStart(animation);
//                        mSplashLogo.setVisibility(View.VISIBLE);
//                    }
//                });
//        mSplashLogo.startAnimation(scale);
//    }

//    private void startBottomAnim() {
//        Animation translate = AnimUtil.translate(0, 0,
//                mSplashBottom.getHeight(), -DensityUtil.dp2px(30), 150,
//                new LinearInterpolator(), null);
//
//        Animation scale = AnimUtil.Scale(0f, 1f, 0f, 1f,
//                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f,
//                150, new LinearInterpolator(), null);
//
//        AnimationSet animationSet = AnimUtil.aminSet(true,
//                150, new LinearInterpolator(), translate, scale);
//        animationSet.setFillAfter(true);
//
//        mSplashBottom.startAnimation(animationSet);
//    }

//    public void startLogoTextAnim() {
//        Animation translate = AnimUtil.translate(0, 0,
//                DensityUtil.dp2px(40), 0, 150,
//                new LinearInterpolator(), null);
//
//        Animation alpha = AnimUtil.alpha(0.2f, 1,
//                300, new LinearInterpolator(), null);
//
//        AnimationSet animationSet = AnimUtil.aminSet(true,
//                150, new LinearInterpolator(), translate, alpha);
//        animationSet.setFillAfter(true);
//
//        mSplashLogoText.startAnimation(animationSet);
//    }

//    public void startLoginLightBgAnim() {
//        Animation alpha = AnimUtil.alpha(0.2f, 1,
//                1000, new LinearInterpolator(), new AnimListener() {
//                    @Override
//                    public void onAnimationEnd(Animation animation) {
//                        super.onAnimationEnd(animation);
//                        mSplashHandler.sendEmptyMessageDelayed(CHECK_UPDATE, 0);
//                    }
//                });
//        alpha.setFillAfter(true);
//        mSplashLogoLightBg.startAnimation(alpha);
//
//    }
//
//    public void startLoginLightAnim() {
//        Animation alpha = AnimUtil.alpha(0.2f, 1,
//                600, new LinearInterpolator(), null);
//        alpha.setFillAfter(true);
//        mSplashLogoLight.startAnimation(alpha);
//    }

//    /**
//     * 下载进度的展示
//     *
//     * @param myInfo
//     */
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void downInfo(MyInfo<Download> myInfo) {
//        if (myInfo.getType() == MyInfo.MyInfoEnum.downinfo) {
//            Download download = myInfo.getData();
//
//            if (mTv.getVisibility() != View.VISIBLE) {
//                mTv.setVisibility(View.VISIBLE);
//                mTips.setVisibility(View.VISIBLE);
//            }
//
//            if (download.getProgress() == 100) {
//                mTv.setText("下载完成");
//            } else {
//                mTv.setText(U.connectString(StringUtils.getDataSize(download.getCurrentFileSize()),
//                        "/", StringUtils.getDataSize(download.getTotalFileSize())));
//            }
//        } else if (myInfo.getType() == MyInfo.MyInfoEnum.downerror) {
//            mTv.setVisibility(View.INVISIBLE);
//            if (mIsUpdate) {
//                showMessage("下载失败");
//                finish();
//            } else {
//                goHome();
//            }
//        }
//    }

//    /**
//     * 下载完成
//     *
//     * @param myInfo
//     */
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void downOver(MyInfo<File> myInfo) {
//        if (myInfo.getType() == MyInfo.MyInfoEnum.installApp) {
//            installApk(myInfo.getData());
//        }
//    }

//    /**
//     * 检查更新
//     */
//    public void checkUpdate() {
//        AppInfo appInfo = U.getAppInfo(this);
////        mPresenter.checkUpdate(Constant.PLATFORM,appInfo.getVersionName());
//
//        //
//        startActivity(new Intent(this, HomeActivity.class));
//        finish();
//    }
    @Override
    public void checkOk(HttpWrapper<Version> data) {
        mData = data;

//        check();
    }

//    public void check() {
//        Version version = mData.getData();
//        if (version != null) {
//            mDownloadUrl = version.getDownloadUrl();
//        }
//
//        if (Constant.SUCCESS_CODE.equals(mData.getCode())) {
//            if (version.getHaveNewVersion() == 1) {
//                //需要更新
//                if (version.getForceUpdate() == 1) {
//                    mIsUpdate = true;
//                } else if (version.getForceUpdate() == 0) {
//                }
//                createVeriosnDialog();
//            } else if (version.getHaveNewVersion() == 0) {
//                //不需要更新
//                goHome();
//            }
//        } else if ("203".equals(mData.getCode())) {
//            mIsUpdate = true;
//            createVeriosnDialog();
//        } else {
//            mTv.setText("没有检测到新版本");
//            long endTime = System.currentTimeMillis();
//            if (endTime - mStartTime < 2000) {
//                mDTime = endTime - mStartTime;
//                Observable.just(mDTime)
//                        .delay(mDTime, TimeUnit.MILLISECONDS)
//                        .subscribe(v -> {
//                            Logger.i("不需要更新延迟进入主页");
//                            goHome();
//                        }, error -> goHome());
//            } else {
//                goHome();
//            }
//        }
//    }

//    private void createVeriosnDialog() {
//        if (mIsUpdate) {
//            U.getSingleDialog(this, "提示", "当前版本较低,点击升级版本!", "升级", this::downloadApk).show();
//        } else {
//            U.getSlectDialog(this, "提示", "当前版本较低,点击升级版本!", "暂不升级", "升级", new Listener.OnNormalAlertDialogChooseClickListener() {
//                @Override
//                public void onLeft() {
//                    goHome();
//                }
//
//                @Override
//                public void onRight() {
//                    downloadApk();
//                }
//            }).show();
//        }
//        mTv.setText("检测到新版本");
//    }

    @Override
    public void error() {
        goHome();
    }

    protected void goHome() {
        mRxPermissions
                .request(Manifest.permission.READ_PHONE_STATE
                        , Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE
                        , Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        go();
                    }

                    @Override
                    public void onError(Throwable e) {
                        go();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void go() {

        /**
         * 判断是否记载了splash页面
         */
        boolean guide = AppCenter.mSpUtil.getBoolean(Constant.GUIDE, false);
        if (guide) {
            Logger.i("进入主页面");
            // 开启主界面Activity
            startActivity(new Intent(this, HomeActivity.class));
            finish();
        } else {
            Logger.i("进入guide页面");
            // 开启GuideActivity
            startActivity(new Intent(this, GuideActivity.class));
            finish();
        }
    }

    /**
     * 安装apk
     *
     * @param file
     */
    protected void installApk(File file) {
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        /**
         * 适配android7.0
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(this, Constant.PACKAGE + ".fileprovider", file);
            intent.setDataAndType(contentUri,
                    "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file),
                    "application/vnd.android.package-archive");
        }
        startActivityForResult(intent, REQUEST_CODE_UPDATE);
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mIntent != null) {
            stopService(mIntent);
        }
//        EventBus.getDefault().unregister(this);
    }

    /**
     * 下载apk
     */
    public void downloadApk() {
        mRxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        mIntent = new Intent(SplashActivity.this, DownloadService.class);
                        mIntent.putExtra("url", mDownloadUrl);
                        startService(mIntent);
                    } else {
                        finish();
                    }
                });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_splash;
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

}
